﻿// MedicalRulesEngine.API/Extensions/HealthCheckExtensions.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;
using MedicalRulesEngine.Infrastructure.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace MedicalRulesEngine.API.Extensions;

/// <summary>
/// 健康检查配置扩展
/// </summary>
public static class HealthCheckExtensions
{
    /// <summary>
    /// 添加健康检查
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
    {
        var healthChecksBuilder = services.AddHealthChecks();

        // 数据库健康检查
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        if (!string.IsNullOrWhiteSpace(connectionString))
        {
            healthChecksBuilder.AddDbContextCheck<RulesDbContext>("database", HealthStatus.Degraded);
        }

        // 内存使用检查
        healthChecksBuilder.AddCheck<MemoryHealthCheck>("memory");

        // 磁盘空间检查
        healthChecksBuilder.AddCheck<DiskSpaceHealthCheck>("disk_space");

        // 自定义规则引擎健康检查
        healthChecksBuilder.AddCheck<RulesEngineHealthCheck>("rules_engine");

        return services;
    }
}

/// <summary>
/// 内存健康检查
/// </summary>
public class MemoryHealthCheck : IHealthCheck
{
    private const long MaxMemoryUsageBytes = 1024 * 1024 * 1024; // 1GB

    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        var memoryUsage = GC.GetTotalMemory(false);

        if (memoryUsage > MaxMemoryUsageBytes)
        {
            return Task.FromResult(HealthCheckResult.Unhealthy($"内存使用过高: {memoryUsage / 1024 / 1024}MB"));
        }

        if (memoryUsage > MaxMemoryUsageBytes * 0.8)
        {
            return Task.FromResult(HealthCheckResult.Degraded($"内存使用较高: {memoryUsage / 1024 / 1024}MB"));
        }

        return Task.FromResult(HealthCheckResult.Healthy($"内存使用正常: {memoryUsage / 1024 / 1024}MB"));
    }
}

/// <summary>
/// 磁盘空间健康检查
/// </summary>
public class DiskSpaceHealthCheck : IHealthCheck
{
    private const long MinFreeSpaceBytes = 1024 * 1024 * 1024; // 1GB

    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            var drive = new DriveInfo(Directory.GetCurrentDirectory());
            var freeSpace = drive.AvailableFreeSpace;

            if (freeSpace < MinFreeSpaceBytes)
            {
                return Task.FromResult(HealthCheckResult.Unhealthy($"磁盘空间不足: {freeSpace / 1024 / 1024}MB"));
            }

            if (freeSpace < MinFreeSpaceBytes * 2)
            {
                return Task.FromResult(HealthCheckResult.Degraded($"磁盘空间较低: {freeSpace / 1024 / 1024}MB"));
            }

            return Task.FromResult(HealthCheckResult.Healthy($"磁盘空间充足: {freeSpace / 1024 / 1024}MB"));
        }
        catch (Exception ex)
        {
            return Task.FromResult(HealthCheckResult.Unhealthy($"检查磁盘空间时发生错误: {ex.Message}"));
        }
    }
}

/// <summary>
/// 规则引擎健康检查
/// </summary>
public class RulesEngineHealthCheck : IHealthCheck
{
    private readonly RulesEngine.RulesEngine _rulesEngine;

    public RulesEngineHealthCheck(RulesEngine.RulesEngine rulesEngine)
    {
        _rulesEngine = rulesEngine ?? throw new ArgumentNullException(nameof(rulesEngine));
    }

    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            // 创建一个简单的测试规则
            var testWorkflow = new RulesEngine.Models.Workflow
            {
                WorkflowName = "HealthCheck",
                Rules = new List<RulesEngine.Models.Rule>
                {
                    new RulesEngine.Models.Rule
                    {
                        RuleName = "TestRule",
                        Expression = "true"
                    }
                }
            };

            // 执行测试规则
            var result = await _rulesEngine.ExecuteAllRulesAsync("HealthCheck", new { });

            if (result != null && result.Any())
            {
                return HealthCheckResult.Healthy("规则引擎运行正常");
            }

            return HealthCheckResult.Degraded("规则引擎响应异常");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy($"规则引擎检查失败: {ex.Message}");
        }
    }
}
